import 'dart:async';
import 'package:flutter/material.dart';
import 'ddl_card.dart';
import '../models/ddl_item.dart';
import '../app_data_manager.dart';

class DDLList extends StatefulWidget {
  final List<DDLItem> ddls;

  const DDLList({super.key, required this.ddls});

  @override
  State<DDLList> createState() => _DDLListState();
}

class _DDLListState extends State<DDLList> {
  Timer? _timer;
  final _appDataManager = AppDataManager();

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(const Duration(minutes: 1), (timer) {
      if (mounted) setState(() {});
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Center(
              child: Text(
                'DDL表',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
            ),
            const SizedBox(height: 8),
            if (widget.ddls.isEmpty)
              const Center(child: Text('暂无DDL'))
            else
              ...widget.ddls.map((ddl) => DDLCard(
                    ddl: ddl,
                    onStatusChanged: (status) async {
                      setState(() {
                        ddl.isCompleted = status == '已完成';
                      });
                      // 更新数据并保存
                      await _appDataManager.saveDDLList(widget.ddls);
                    },
                  )),
          ],
        ),
      ),
    );
  }
}
